
package com.myproject.myblogserver.controller;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myproject.myblogserver.contant.CommonConstants;
import com.myproject.myblogserver.dto.PageResultDto;
import com.myproject.myblogserver.dto.blog.BlogPreviewDto;
import com.myproject.myblogserver.entity.Blog;
import com.myproject.myblogserver.entity.ViewHistory;
import com.myproject.myblogserver.service.IBlogService;
import com.myproject.myblogserver.service.IViewHistoryService;
import com.myproject.myblogserver.utils.JwtUtil;

/**
 * <p>
 * 浏览历史表 前端控制器
 * </p>
 *
 * @author jiangweike
 * @since 2025-02-16
 */
@Controller
@RequestMapping("/viewHistory")
public class ViewHistoryController {

    @Autowired
    private IViewHistoryService viewHistoryService;

    @Autowired
    private IBlogService blogService;

    @PostMapping("/add/{blogId}")
    public ResponseEntity<?> add(@PathVariable Long blogId,
            @RequestHeader("Authorization") String authHeader) {
        try {
            var userId = JwtUtil.extractUserIdFromAuthHeader(authHeader);

            // 检查博客是否存在
            var blog = blogService.lambdaQuery()
                    .eq(Blog::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                    .eq(Blog::getId, blogId)
                    .one();

            if (blog == null) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("博客不存在！");
            }

            // 检查是否已有浏览记录
            var existingHistory = viewHistoryService.lambdaQuery()
                    .eq(ViewHistory::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                    .eq(ViewHistory::getUserId, userId)
                    .eq(ViewHistory::getBlogId, blogId)
                    .one();

            if (existingHistory != null) {
                // 更新浏览时间
                viewHistoryService.lambdaUpdate()
                        .set(ViewHistory::getViewTime, LocalDateTime.now())
                        .eq(ViewHistory::getId, existingHistory.getId())
                        .update();
            } else {
                // 创建新的浏览记录
                var viewHistory = new ViewHistory();
                viewHistory.setBlogId(blogId);
                viewHistory.setUserId(userId);
                viewHistoryService.save(viewHistory);
            }

            return ResponseEntity.ok("添加浏览记录成功！");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("添加浏览记录失败！");
        }
    }

    @GetMapping("/list/{pageIndex}")
    public ResponseEntity<?> list(@PathVariable Integer pageIndex,
            @RequestHeader("Authorization") String authHeader) {
        try {
            var userId = JwtUtil.extractUserIdFromAuthHeader(authHeader);

            // 分页获取用户的浏览记录
            var historyPage = viewHistoryService.lambdaQuery()
                    .eq(ViewHistory::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                    .eq(ViewHistory::getUserId, userId)
                    .orderByDesc(ViewHistory::getViewTime)
                    .page(new Page<>(pageIndex, CommonConstants.DEFAULT_PAGE_SIZE));

            var blogIds = historyPage.getRecords().stream()
                    .map(ViewHistory::getBlogId)
                    .collect(Collectors.toList());

            var blogPreviews = new ArrayList<BlogPreviewDto>();

            if (!blogIds.isEmpty()) {
                // 获取博客信息
                var blogs = blogService.lambdaQuery()
                        .eq(Blog::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                        .in(Blog::getId, blogIds)
                        .select(Blog::getId, Blog::getTitle, Blog::getSummary, Blog::getCreatedAt)
                        .list();

                // 创建博客ID到博客信息的映射
                var blogMap = blogs.stream()
                        .collect(Collectors.toMap(Blog::getId, blog -> blog));

                // 按浏览记录的顺序组装博客预览数据
                for (var history : historyPage.getRecords()) {
                    var blog = blogMap.get(history.getBlogId());
                    if (blog != null) {
                        var preview = BlogPreviewDto.builder().build();
                        preview.setId(blog.getId());
                        preview.setTitle(blog.getTitle());
                        preview.setSummary(blog.getSummary());
                        preview.setCreatedAt(blog.getCreatedAt());
                        blogPreviews.add(preview);
                    }
                }
            }

            // 构建分页结果
            var pageResult = new PageResultDto<BlogPreviewDto>();
            pageResult.setContent(blogPreviews);
            pageResult.setTotalPages(historyPage.getPages());

            return ResponseEntity.ok(pageResult);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("获取浏览记录失败！");
        }
    }
}
